﻿using Prism.Navigation;
using Prism.Navigation.TabbedPages;
using TangReadyV1.Data;
using TangReadyV1.Models;
using TangReadyV1.Services;
using TangReadyV1.ViewModels;
using SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xamarin.Forms;

namespace TangReadyV1.Views
{
    public partial class PageParam : ContentPage
    {
        private bool isPageActive;
        List<SKFSZ> commonList;
        List<SKFSZ> aList2 ;

        List<CommonFS> aListFromTable;


        private ServiceReferenceGet.GetSkfsDataClient getSkfsClient = null;
        private ServiceReferenceReg.Service1Client cloudClient = null;

        

        string deviceIdentifier = string.Empty;
        private bool sinceChanged = false;

        public PageParam()
        {
            InitializeComponent();
            ((PageParamViewModel)BindingContext).IsActiveChanged += PageParam_IsActiveChanged;
            commonList = new List<SKFSZ>();
            aList2 = new List<SKFSZ>();//??
            deviceIdentifier = DependencyService.Get<IDevice>().GetIdentifier();
          
            //默认的test 
            cloudClient = new ServiceReferenceReg.Service1Client();

            sinceChanged = false;
            this.SaveZFFS.IsEnabled = false;
            listView.ItemsSource = aListFromTable;
            this.Appearing += PageParam_Appearing;
        }

        private void PageParam_Appearing(object sender, EventArgs e)
        {
            // throw new NotImplementedException();
            this.Title = ((PageParamViewModel)BindingContext).Title + "  (" + deviceIdentifier + ")";


            this.loginGrid.IsVisible = true;
            this.retMsg.Text = App.Cloud_RetMsg;
            this.password.Text = string.Empty;

            activityIndicator.IsRunning = true;


            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
            Pull_all_ZFFS_ToLocal(path);

            if (aListFromTable != null)
            {

                listView.ItemsSource = aListFromTable;
                // listView.Refresh();
            }

            sinceChanged = false;
            this.SaveZFFS.IsEnabled = false;
            activityIndicator.IsRunning = false;

        }

        private void  CreateMockData()
        {          
            aList2.Add(new SKFSZ() { CODE = 16, NAME = "现金", CODESpecified = true, IsChecked = true });
            aList2.Add(new SKFSZ() { CODE = 17, NAME = "微信", CODESpecified = true, IsChecked = true });
            aList2.Add(new SKFSZ() { CODE = 22, NAME = "支付宝", CODESpecified = true, IsChecked = true });
            aList2.Add(new SKFSZ() { CODE = 26, NAME = "银联卡", CODESpecified = true, IsChecked = false });
            aList2.Add(new SKFSZ() { CODE = 97, NAME = "消费券", CODESpecified = true, IsChecked = true });
            aList2.Add(new SKFSZ() { CODE = 90, NAME = "抵扣券", CODESpecified = true, IsChecked = true });           
        }
        private void PageParam_IsActiveChanged(object sender, EventArgs e)
        {
            //   throw new NotImplementedException();
            if (((PageParamViewModel)BindingContext).IsActive)
            {
                this.Title = ((PageParamViewModel)BindingContext).Title+"  (" + deviceIdentifier+")";

                //从全局变量或者说是已经保存的参数信息  更新UI控件


             //   this.entCashierNo.Text= App.sktNo ;

                this.entShop.Text=App.shopName;
                this.entMarket.Text =App.marketName ;
            //    this.entItemCode.Text= App.spCode ;
                this.checkNormal.IsChecked = !App.bNormalOperation;

                this.entItemCloud.Text = App.CloudUrl;



                this.loginGrid.IsVisible = true;
                this.retMsg.Text = App.Cloud_RetMsg;
                 this.password.Text = string.Empty;

                activityIndicator.IsRunning = true;


                var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
                Pull_all_ZFFS_ToLocal(path);
               
                if (aListFromTable!=null)
                {
               
                listView.ItemsSource = aListFromTable;
               // listView.Refresh();
                }

                sinceChanged = false;
                this.SaveZFFS.IsEnabled = false;
                activityIndicator.IsRunning = false;


            }
        }

      

        private void Refresh_Clicked(object sender, System.EventArgs e)
        {
           

            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
            using (SQLiteConnection con = new SQLiteConnection(path))
            {          

                //con.CreateTable<GlobalParams>();       

                //con.CreateTable<CommonFS>();                 
          

                if (aListFromTable!=null)
                {
                    foreach (var item in aListFromTable)
                    {
                        con.InsertOrReplace(item);
                    }
                }         

            }
            Pull_all_ZFFS_ToLocal(path);

            listView.ItemsSource = aListFromTable;

            sinceChanged = false;
            this.SaveZFFS.IsEnabled = false;
        }

            private async void getZFFS_Clicked(object sender, System.EventArgs e)
        {
            activityIndicator.IsRunning = true;
           

         //   getSkfsClient = new ServiceReferenceGet.GetSkfsDataClient();

            if ((bool)this.checkNormal.IsChecked)
            {
               
                //call the test website

                //   getSkfsClient = new ServiceReferenceGet.GetSkfsDataClient(ServiceReferenceGet.GetSkfsDataClient.EndpointConfiguration.BasicHttpBinding_IGetSkfsData, "http://27.115.22.198:6666/GetSkfsData.svc");
                getSkfsClient = new ServiceReferenceGet.GetSkfsDataClient(ServiceReferenceGet.GetSkfsDataClient.EndpointConfiguration.BasicHttpBinding_IGetSkfsData, this.entItemWebTest.Text+ @"/GetSkfsData.svc");

                App.bNormalOperation = false;
            }
            else
            {
                //   getSkfsClient = new ServiceReferenceGet.GetSkfsDataClient(ServiceReferenceGet.GetSkfsDataClient.EndpointConfiguration.BasicHttpBinding_IGetSkfsData, "http://180.168.154.8:6666/GetSkfsData.svc");
                getSkfsClient = new ServiceReferenceGet.GetSkfsDataClient(ServiceReferenceGet.GetSkfsDataClient.EndpointConfiguration.BasicHttpBinding_IGetSkfsData, this.entWeb.Text + @"/GetSkfsData.svc");
                          
                App.bNormalOperation = true;
            }

           
            //获取支付方式列表
            List<SKFSZ> zffsList = new List<SKFSZ>();

             ServiceReferenceGet.SKFSMoudle aMoudle = getSkfsClient.GetSkfsData();


           await getSkfsClient.CloseAsync();


            if (aMoudle!=null)
            {
                for (int i = 0; i < aMoudle.Data.Length - 1; i++)
                {
                    zffsList.Add(new SKFSZ() { CODE = aMoudle.Data[i].CODE, NAME = aMoudle.Data[i].NAME, });
                }
            }


            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
            using (SQLiteConnection con = new SQLiteConnection(path))
            {
              //  con.CreateTable<CommonFS>();

                foreach (var item in zffsList)
                {
                    // con.Insert( new CommonFS() { CODE=item.CODE,NAME=item.NAME,IsChecked=item.IsChecked });
                    CommonFS cm = con.Table<CommonFS>().Where(a => a.CODE == item.CODE).FirstOrDefault();
                    if (cm == null)
                    {

                        con.Insert(new CommonFS() { CODE = item.CODE, NAME = item.NAME, IsChecked = item.IsChecked });
                    }
                    else
                    {
                        cm.NAME = item.NAME;
                        con.InsertOrReplace(cm);
                    }
                }


            }
            Pull_all_ZFFS_ToLocal(path);

            //   commonList = new List<SKFSZ>(aList);
            //    aList2 = commonList;
            //  listView.ItemsSource = aList2.ToList();
            listView.ItemsSource = aListFromTable;
            activityIndicator.IsRunning = false;

        }

        private void Pull_all_ZFFS_ToLocal(string path)
        {
            using (SQLiteConnection con = new SQLiteConnection(path))
            {

                List<CommonFS> fromTable = con.Table<CommonFS>().ToList();

                if (fromTable != null)
                {
                    aListFromTable = fromTable.OrderByDescending(bb => bb.IsChecked).ThenBy(bb => bb.CODE).ToList();
                }
            }
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
           // this.password.Text = "1";
            if (this.password.Text==DateTime.Now.ToString("yyyyMMdd"))
            {
                this.password.Text = string.Empty;
                

                this.loginGrid.IsVisible = false;
                //    this.getZFFS.Focus(); entItemCloud
                //  this.entCashierNo.Focus();
                this.entItemCloud.Focus();

                //if (aListFromTable != null)
                //{
                //    listView.ItemsSource = aListFromTable;
                //}
            }
            else
            {
                DisplayAlert("不能进入", "请重新输入参数调试密码", "OK");
                this.password.Text = string.Empty;
                this.password.Focus();
                return;
            }
        }

        
        private async void  btnSave_Clicked(object sender, EventArgs e)
        {
            //  string deviceIdentifier = DependencyService.Get<IDevice>().GetIdentifier();
            string msg;
            string retShop;
            string retMarket;
            //App.bSaveParam = true;

            //更新全局变量

            if (sinceChanged )
            {
                await  DisplayAlert("常用支付发生变化","请先点击(保存常用支付)按钮" , "OK!");
                return;
            }

            //保存除支付方式外的其他设置 为什么和APP一样？因为可能已经有变化
            App.sktNo = this.entCashierNo.Text;
            App.shopName = this.entShop.Text;
            App.marketName = this.entMarket.Text;
            App.spCode = this.entItemCode.Text;
            App.bNormalOperation = !(bool)this.checkNormal.IsChecked;
            App.CloudUrl = this.entItemCloud.Text;

            //保存云服务器URL
          //  App.DestNew = this.entItemCloud.Text;


            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
            using (SQLiteConnection con = new SQLiteConnection(path))
            {
               // con.CreateTable<GlobalParams>();
                GlobalParams by2 = con.Table<GlobalParams>().FirstOrDefault();
                if (by2==null)
                {
                    by2 = new GlobalParams();
                }
                by2.SKTNO = this.entCashierNo.Text;
                by2.ShopName = this.entShop.Text;
                by2.MarketName = this.entMarket.Text;
                by2.SPCode = this.entItemCode.Text;
                if ((bool)this.checkNormal.IsChecked)
                {
                    by2.WebServiceUrl = this.entItemWebTest.Text;
                }
                else
                {
                    by2.WebServiceUrl = this.entWeb.Text;
                }             
                by2.BNormalAddress= !(bool)this.checkNormal.IsChecked;
              
                by2.CloudUrl= this.entItemCloud.Text;

             //   App.CloudUrl = by2.WebServiceUrl;
             
                //访问外部商家WCF
                App.DestNew = by2.WebServiceUrl;
                // con.Insert(by2); 
                con.InsertOrReplace(by2);

            }
            //   cloudService.ChangeUrl(this.entItemCloud.Text);  
           
            //腾讯云服务URL
          

            //默认的test 
            cloudClient = new ServiceReferenceReg.Service1Client(ServiceReferenceReg.Service1Client.EndpointConfiguration.BasicHttpBinding_IService1, App.CloudUrl+ @":8052/Service1.svc");

            bool bExisted = cloudClient.Exist(this.entCashierNo.Text, this.entShop.Text, this.entMarket.Text, this.entItemCode.Text, deviceIdentifier, DateTime.Now, out msg,out retShop,out retMarket);

          //  bool bExisted = client2.Exist(this.entCashierNo.Text, this.entShop.Text, this.entMarket.Text, this.entItemCode.Text, deviceIdentifier, DateTime.Now, out msg);
            if (!bExisted)
            {
                if (msg == "首次运行，请先进行参数设置操作")
                {
                    bool bInserts = cloudClient.RegisterNew(this.entCashierNo.Text, this.entShop.Text, this.entMarket.Text, this.entItemCode.Text, deviceIdentifier, DateTime.Now, out msg);
                    if (bInserts)
                    {
                        App.Cloud_RetMsg = "";
                        await DisplayAlert("注册提示", "新终端注册成功!", "OK!");
                    }
                }
                else
                {
                       await DisplayAlert("提示", msg, "OK!");
                       return;
                }
               
            }
            else
            {
                await DisplayAlert("提示 YY  ", retShop + retMarket, "OK!");
                return; 
            }

            await cloudClient.CloseAsync();

                //状态复位
                sinceChanged = false;

            //合法用户
                App.Cloud_RetMsg = "";
               await DisplayAlert("提示", "参数设置保存成功", "OK!");

                await ((PageParamViewModel)BindingContext)._navigationService.SelectTabAsync("PageUpload");

            

            //   await client2.CloseAsync();
        }

        private void checkNormal_StateChanged(object sender, Syncfusion.XForms.Buttons.StateChangedEventArgs e)
        {
           
        }

     

        private void listView_ValueChanged(object sender, Syncfusion.SfDataGrid.XForms.ValueChangedEventArgs e)
        {
            sinceChanged = true;
            this.SaveZFFS.IsEnabled = true;
        }

    }
}
